<template>
  <view class="signin-container">
    <!-- 顶部信息 -->
    <view class="header">
      <view class="points">当前积分: {{points}}</view>
      <view class="continuous">已连续签到: {{continuousDays}}天</view>
    </view>

    <!-- 日历区域 -->
    <view class="calendar">
      <view class="month-header">
        <text class="arrow" @click="prevMonth">◀</text>
        <text class="month-title">{{currentYear}}年{{currentMonth}}月</text>
        <text class="arrow" @click="nextMonth">▶</text>
      </view>

      <view class="weekdays">
        <view class="weekday" v-for="day in ['日','一','二','三','四','五','六']" :key="day">{{day}}</view>
      </view>

      <view class="days">
        <view v-for="(day, index) in calendarDays" :key="index" :class="['day', {
            'today': day.isToday,
            'signed': day.signed,
            'current-month': day.isCurrentMonth,
            'can-sign': day.canSign
          }]" @click="handleDayClick(day)">
          <text>{{day.day}}</text>
          <text class="sign-mark" v-if="day.signed">✓</text>
        </view>
      </view>
    </view>

    <!-- 签到按钮 -->
    <button class="signin-btn" :disabled="todaySigned" @click="handleSignIn">
      {{todaySigned ? '今日已签到' : '立即签到'}}
    </button>

    <!-- 签到奖励提示 -->
    <view class="reward-tip" v-if="showRewardTip">
      签到成功! +{{todayReward}}积分
      <text v-if="continuousDays >= 3"> (连续签到奖励)</text>
    </view>

    <!-- 签到规则 -->
    <view class="rules">
      <view class="rule-title">签到规则:</view>
      <view>1. 每日签到可获得{{baseReward}}积分</view>
      <view>2. 连续签到3天以上可获得额外奖励</view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      points: 100, // 当前积分
      baseReward: 10, // 基础奖励
      extraReward: 5, // 额外奖励
      todayReward: 0, // 今日奖励
      showRewardTip: false, // 显示奖励提示
      todaySigned: false, // 今日是否已签到
      continuousDays: 0, // 连续签到天数
      currentYear: new Date().getFullYear(),
      currentMonth: new Date().getMonth() + 1,
      signedDates: [], // 已签到的日期数组
      calendarDays: [] // 日历天数数组
    }
  },
  created() {
    this.loadSignData()
  },
  methods: {
    // 加载签到数据
    async loadSignData() {
      try {
        const { data } = await uni.$http.get('/sign')
        if (data.code !== 1) throw new Error(data.message || '加载签到数据失败')
        
        // 从API加载已签到数据
        const signData = data.data || {}
        this.points = signData.points || 100
        this.signedDates = signData.signedDates || []
        
        this.continuousDays = signData.continuousDays || 0

        // 检查今天是否已签到
        const todayStr = this.formatDate(new Date())
        this.todaySigned = this.signedDates.includes(todayStr)
        this.generateCalendar()
      } catch (err) {
        console.error('加载签到数据失败:', err)
        uni.showToast({
          title: '加载签到数据失败',
          icon: 'none'
        })
      }
    },

    // 生成日历
    generateCalendar() {
      const days = []
      const date = new Date(this.currentYear, this.currentMonth - 1, 1)
      const daysInMonth = new Date(this.currentYear, this.currentMonth, 0).getDate()
      const firstDay = new Date(this.currentYear, this.currentMonth - 1, 1).getDay()
      
      // 上个月的最后几天
      const prevMonthDays = new Date(this.currentYear, this.currentMonth - 1, 0).getDate()
      for (let i = 0; i < firstDay; i++) {
        days.push({
          day: prevMonthDays - firstDay + i + 1,
          isCurrentMonth: false,
          signed: false,
          canSign: false
        })
      }

      // 当前月的天数
      const today = new Date()
      const todayStr = this.formatDate(today)
      for (let i = 1; i <= daysInMonth; i++) {
        const currentDate = new Date(this.currentYear, this.currentMonth - 1, i)
        const dateStr = this.formatDate(currentDate)
        const isToday = dateStr === todayStr
        const signed = this.signedDates.includes(dateStr)
        days.push({
          day: i,
          isCurrentMonth: true,
          isToday: isToday,
          signed: signed,
          canSign: isToday && !signed
        })
      }
      
      // 下个月的前几天
      const totalCells = Math.ceil(days.length / 7) * 7
      for (let i = 1; i <= totalCells - days.length; i++) {
        days.push({
          day: i,
          isCurrentMonth: false,
          signed: false,
          canSign: false
        })
      }

      this.calendarDays = days
    },

    // 格式化日期为 YYYY-MM-DD
    formatDate(date) {
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      return `${year}-${month}-${day}`
    },

    // 切换月份
    prevMonth() {
      if (this.currentMonth === 1) {
        this.currentYear--
        this.currentMonth = 12
      } else {
        this.currentMonth--
      }
      this.generateCalendar()
    },

    nextMonth() {
      if (this.currentMonth === 12) {
        this.currentYear++
        this.currentMonth = 1
      } else {
        this.currentMonth++
      }
      this.generateCalendar()
    },

    // 处理签到
    handleSignIn() {
      if (this.todaySigned) return

      const today = new Date()
      const todayStr = this.formatDate(today)

      // 计算连续签到
      const yesterday = new Date(today)
      yesterday.setDate(yesterday.getDate() - 1)
      const yesterdayStr = this.formatDate(yesterday)

      if (this.signedDates.includes(yesterdayStr)) {
        this.continuousDays++
      } else {
        // 如果不是连续签到，重置为1
        this.continuousDays = 1
      }

      // 计算奖励
      this.todayReward = this.baseReward
      if (this.continuousDays >= 3) {
        this.todayReward += this.extraReward
      }

      // 更新状态
      this.points += this.todayReward
      this.signedDates.push(todayStr)
      this.todaySigned = true
      this.showRewardTip = true

      // 保存数据
      this.saveSignData()

      // 更新日历
      this.generateCalendar()

      // 3秒后隐藏奖励提示
      setTimeout(() => {
        this.showRewardTip = false
      }, 3000)
    },

    // 保存签到数据
    saveSignData() {
      const signData = {
        points: this.points,
        signedDates: this.signedDates,
        continuousDays: this.continuousDays
      }
      
      uni.$http.post('/sign', signData)
        .then(({ data }) => {
          if (data.code !== 1) throw new Error(data.message || '保存数据失败')
          uni.showToast({
            title: '签到成功',
            icon: 'success'
          })
        })
        .catch(err => {
          console.error('保存签到数据失败:', err)
          uni.showToast({
            title: '保存签到数据失败',
            icon: 'none'
          })
        })
    },

    // 点击日期
    handleDayClick(day) {
      if (!day.isCurrentMonth || !day.canSign) return
      this.handleSignIn()
    }
  }
}
</script>

<style lang="scss">
.signin-container {
  padding: 20rpx;
}

.header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 30rpx;
  font-size: 28rpx;
  color: #666;
}

.calendar {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 20rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
}

.month-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
  font-size: 32rpx;
  font-weight: bold;
}

.arrow {
  font-size: 36rpx;
  padding: 0 20rpx;
  color: #666;
}

.weekdays {
  display: flex;
  margin-bottom: 20rpx;
}

.weekday {
  flex: 1;
  text-align: center;
  font-size: 28rpx;
  color: #666;
}

.days {
  display: flex;
  flex-wrap: wrap;
}

.day {
  width: 14.28%;
  height: 80rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
  font-size: 28rpx;
  color: #999;
}

.day.current-month {
  color: #333;
}

.day.today {
  font-weight: bold;
  color: #07C160;
}

.day.can-sign {
  background-color: #f5f5f5;
  border-radius: 50%;
}

.day.signed .sign-mark {
  position: absolute;
  bottom: 6rpx;
  right: 6rpx;
  font-size: 20rpx;
  color: #07C160;
}

.signin-btn {
  margin-top: 40rpx;
  background-color: #07C160;
  color: white;
  border-radius: 50rpx;
}

.signin-btn[disabled] {
  background-color: #ccc;
}

.reward-tip {
  margin-top: 20rpx;
  text-align: center;
  color: #07C160;
  font-size: 28rpx;
}

.rules {
  margin-top: 40rpx;
  padding: 20rpx;
  background-color: #f9f9f9;
  border-radius: 12rpx;
  font-size: 26rpx;
  color: #666;
}

.rule-title {
  font-weight: bold;
  margin-bottom: 10rpx;
  color: #333;
}
</style>  